﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quartz.Impl;
using Quartz.Spi;
using Quartz.Net.Model;
using Quartz.Net.Factory;
using Newtonsoft.Json;

namespace Quartz.Net.Core.Listener
{
   public class myTriggerListener:ITriggerListener
    {
       private string name;
       public string Name { get { return "myTriggerListener"; } set { name = value; } }

        public void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)
        {
            //throw new NotImplementedException();
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            Task_Quartz_JobTriggerModel list = JsonConvert.DeserializeObject<Task_Quartz_JobTriggerModel>(dataMap.GetString("jobDetails"));
            Console.WriteLine(list.JOBNAME + ":job完成时调用");
            if (!string.IsNullOrWhiteSpace(list.JOBCRON))
            {
                List<DateTime> listDate = QuartzHelper.GetNextFireTime(list.JOBCRON, 2);
                if (DateTime.Compare(listDate[0], DateTime.Now) > 0)
                {
                    factoryClass.TriggerComplete(list.JOBNAME, listDate[0]);
                }
                else
                {
                    factoryClass.TriggerComplete(list.JOBNAME, listDate[1]);
                }
            }
            
            
        }

        public void TriggerFired(ITrigger trigger, IJobExecutionContext context)
        {
            //throw new NotImplementedException();
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            Task_Quartz_JobTriggerModel list = JsonConvert.DeserializeObject<Task_Quartz_JobTriggerModel>(dataMap.GetString("jobDetails"));
            Console.WriteLine(list.JOBNAME + ":job执行时调用");
            factoryClass.TriggerFired(list.JOBNAME);
        }

        public void TriggerMisfired(ITrigger trigger)
        {
            //throw new NotImplementedException();
            Console.WriteLine("错过触发时调用(例：线程不够用的情况下)");
            factoryClass.InsertRrrorlog(trigger.JobDataMap.ToString() + ":Job错过触发时调用(例：线程不够用的情况下)", "Job错过触发时调用", LogsStatus.Fatal);
        }

        public bool VetoJobExecution(ITrigger trigger, IJobExecutionContext context)
        {
            Console.WriteLine("VetoJobExecution");
            //throw new NotImplementedException();
            //Trigger触发后，job执行时调用本方法。true即否决，job后面不执行。
            return false;
        }
    }
}
